<?php
/**
 * 框架类
 * @author Leo
 *
 */
class Nutzp {
	/**
	 * 运行应用
	 * @param string $app
	 * @param string $ioc_cfg_file 指定IOC配置文件
	 */
	public static function run($app = 'default') {
		$ioc = get_current_ioc ();
		$request = $ioc->get ( 'request' );
		//可以在引导文件里设置ACTION_PARAM_NAME以改变请求中对应Action的参数名,默认为act
		$act_arg = (defined ( 'ACTION_PARAM_NAME' ) && ACTION_PARAM_NAME) ? ACTION_PARAM_NAME : 'act';
		$cmd = $request->get ( $act_arg, 'Index' );
		if (is_numeric ( $cmd )) {
			$cmd = 'Index';
		}
		$command_file = APPS . $app . DS . 'actions' . DS . $cmd . '.inc';
		$response = new Response ( null, $app );
		if (is_file ( $command_file )) {
			uses ( APP . '/' . $app . '/actions/' . $cmd . '.inc' );
			if (class_exists ( $cmd ) && is_subclass_of ( $cmd, 'Action' )) {
				$cmdIns = new $cmd ( $app );
				$response->setAction ( $cmdIns );
				$preExec = call_user_func_array ( array ($cmdIns, 'preExec' ), array ($request, $response, $ioc ) );
				if ($preExec !== false) {
					$cached = call_user_func_array ( array ($cmdIns, 'cacheKey' ), array ($request, $ioc ) );
					$render = true; //默认需要绘制				
					if ($cached !== false) { //如果返回了缓存KEY,需要查询缓存以决定缓存能否命中.					
						$cached = $response->preGetCache ( $cached );
					}
					if ($cached === false) { //如果缓存命中只不调用Action.exec
						$render = call_user_func_array ( array ($cmdIns, 'exec' ), array ($request, &$response, $ioc ) );
					}
					if ($render !== false) { //如果返回false则不调用render方法.
						$response->render ( $cached );
					}
				}
			} else {
				$response->error ( "The action {$cmd} of {$app} is not a subclass of Action", 404 );
			}
		} else {
			$response->error ( "The action {$cmd} of {$app} is not found", 404 );
		}
		$response->close (); //关闭
	}
}